package ferp.core.util;

import ferp.core.game.Settings;

/**
 * User: igorgok
 * Date: 12/6/12 4:46 PM
 */
public class Convert
{
  public static String configuration(String current)
  {
    int size = current.length();

    if (size < 6)
    {
      StringBuilder converted = new StringBuilder(current);

      // create new key
      if (size < 5)
        converted.append(Settings.Level.L0.ordinal()).append(Settings.Level.L0.ordinal());

      converted.append(Settings.Tricking10.WHISTED.ordinal());

      return converted.toString();
    }

    return current;
  }

  public static String bin8(int n)
  {
    return pad(8, Integer.toBinaryString(n));
  }

  public static String bin32(int n)
  {
    return pad(32, Integer.toBinaryString(n));
  }

  public static String hex8(int n)
  {
    return "0x" + pad(2, Integer.toHexString(n));
  }

  public static int index(int contract) {return contract - 6;}

  private static String pad(int length, String value)
  {
    StringBuilder sb = new StringBuilder(length);

    for (int i = value.length(); i < length; ++i)
      sb.append('0');

    sb.append(value);

    return sb.toString();
  }

  public static String b2s(byte[] data)
  {
    StringBuilder sb = new StringBuilder(data.length * 2);

    for (byte b : data)
      sb.append(n2h[(b>>4)&0x0F]).append(n2h[b&0x0F]);

    return sb.toString();
  }

  public static byte[] s2b(String data)
  {
    byte[] bytes = new byte[data.length() / 2];

    for (int b = 0, i = 0; b < bytes.length; ++i, ++i, ++b)
    {
      int b0 = Character.digit(data.charAt(i), 16);
      int b1 = Character.digit(data.charAt(i + 1), 16);

      if (b0 == -1 || b1 == -1)
        return null;

      bytes[b] = (byte)((b0 << 4) | b1);
    }

    return bytes;
  }

  // hex conversion table
  private static final char[] n2h = "0123456789abcdef".toCharArray();
}
